<?php

declare(strict_types=1);

namespace App\CustHub\Controller;

use App\CustHub\Service\EasyWorkNotifyService;
use App\CustHub\Service\NotifyService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Mine\MineController;
use function Hyperf\Coroutine\co;

#[Controller(prefix: 'notify')]
class NotifyController extends MineController
{
    #[Inject]
    protected NotifyService $service;

    #[Inject]
    protected EasyWorkNotifyService $easyWorkNotifyService;

    #[RequestMapping('msg')]
    public function msg()
    {
        $params = $this->request->all();

        logger()->info("机器人接收消息：" . json_encode($params, JSON_UNESCAPED_UNICODE));

        if(!isset($params['notice_type'])){
            return 'fail';
        }

        co(function () use ($params){
            $this->service->sync($params);
        });

        return 'success';
    }

    #[RequestMapping('notice')]
    public function notice()
    {
        $params = $this->request->all();
        if(isset($params['code']) && $params['code'] == 0){
            $data = $params['data'];
            $msgTypes = array_column($data, 'msgType');
            if (count(array_unique($msgTypes)) > 1) {
                $data = array_filter($data, function ($item) {
                    return $item['msgType'] != 2118;
                });
                // 重建索引
                $data = array_values($data);
            }

            foreach ($data as $item){
                co(function () use ($item){
                    $item = camelToUnder($item);
                    $this->easyWorkNotifyService->notify($item);
                });
            }
        }
        return 'success';
    }

    #[RequestMapping('test')]
    public function test()
    {
        stdout_log()->info('机器人接收消息：'.json_encode($this->request->all()));
    }
}